extends CharacterBody2D

# 怪物属性
@export var base_attack: int = 3   # 基础攻击力
@export var speed: float = 200.0   # 移动速度
@export var attack_range: float = 100.0  # 攻击范围
var health: int = 500              # 当前生命值

# 移动路径
var target_position: Vector2       # 目标位置（终点）
var target_tower = null            # 当前攻击的目标防御塔
var is_attacking: bool = false     # 是否处于攻击状态
var attack_cooldown: float = 1.0   # 攻击冷却时间
var attack_timer: float = 0.0      # 攻击计时器

func _ready():
	add_to_group("monsters")       # 加入怪物分组
	print("怪物已创建！位置: ", global_position, " 目标位置: ", target_position)
	update_label()

# 更新怪物标签
func update_label():
	if has_node("Label"):
		$Label.text = "葛病\n攻: %d\n命: %d" % [base_attack, health]

# 受到伤害处理
func take_damage(damage: int):
	health -= damage
	update_label()

	
	# 生命值归零时销毁怪物
	if health <= 0:
		print("怪物被击败！")
		queue_free()

# 物理处理（每帧调用）
func _physics_process(delta):
	# 处于攻击状态时处理攻击逻辑
	if is_attacking:
		if target_tower and is_instance_valid(target_tower):
			# 更新攻击计时器
			attack_timer += delta
			
			# 攻击冷却结束
			if attack_timer >= attack_cooldown:
				attack_timer = 0
				target_tower.take_damage(base_attack)
		else:
			# 目标无效时恢复移动
			is_attacking = false
		return
	
	# 移动逻辑：水平移动到终点
	var current_position = global_position
	var target_x = target_position.x
	
	# 计算移动方向
	var move_direction = 1 if target_x > current_position.x else -1
	
	# 只更新X坐标
	current_position.x += move_direction * speed * delta
	
	# 设置新位置
	global_position = current_position
	
	# 检查是否到达终点（水平方向）
	if abs(current_position.x - target_x) < 5:  # 5像素容差
		print("怪物到达终点！")
		queue_free()  # 到达终点时销毁怪物
		return
	
	# 检查附近是否有防御塔
	find_nearby_tower()

# 寻找附近的防御塔
func find_nearby_tower():
	var towers = get_tree().get_nodes_in_group("towers")
	var closest_tower = null
	var min_distance = INF
	
	for tower in towers:
		if is_instance_valid(tower):
			var distance = global_position.distance_to(tower.global_position)
			if distance < min_distance and distance <= attack_range:
				min_distance = distance
				closest_tower = tower
	
	if closest_tower:
		target_tower = closest_tower
		is_attacking = true
